package com.zjl.paike2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjl.paike2.entity.StudentInfo;
import com.zjl.paike2.mapper.StudentInfoMapper;
import com.zjl.paike2.service.StudentInfoService;
import com.zjl.paike2.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 学生信息Service实现类
 */
@Service
public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo> implements StudentInfoService {

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Override
    public List<StudentInfo> getAllStudents() {
        // 查询所有学生（关联班级表）
        return studentInfoMapper.selectStudentList();
    }

    @Override
    public PageResult<StudentInfo> getStudentsByCondition(String stuName, String stuId, String classId, int pageNum, int pageSize) {
        // 使用PageHelper进行分页
        Page<StudentInfo> page = PageHelper.startPage(pageNum, pageSize);
        
        // 条件查询学生列表
        List<StudentInfo> studentList = studentInfoMapper.selectStudentByCondition(stuName, stuId, classId);
        
        // 返回分页结果
        return new PageResult<>(page.getTotal(), studentList);
    }

    @Override
    public StudentInfo getStudentById(String stuId) {
        return studentInfoMapper.selectStudentById(stuId);
    }

    @Override
    public boolean addStudent(StudentInfo studentInfo) {
        // 检查学号是否已存在
        StudentInfo existStudent = getById(studentInfo.getStuId());
        if (existStudent != null) {
            return false;
        }
        
        return save(studentInfo);
    }

    @Override
    public boolean updateStudent(String stuId, StudentInfo studentInfo) {
        // 检查学生是否存在
        StudentInfo existStudent = getById(stuId);
        if (existStudent == null) {
            return false;
        }
        
        // 设置学号
        studentInfo.setStuId(stuId);
        
        // 只更新非空字段
        if (studentInfo.getStuName() == null) {
            studentInfo.setStuName(existStudent.getStuName());
        }
        if (studentInfo.getClassId() == null) {
            studentInfo.setClassId(existStudent.getClassId());
        }
        if (studentInfo.getSex() == null) {
            studentInfo.setSex(existStudent.getSex());
        }
        
        return updateById(studentInfo);
    }

    @Override
    public boolean deleteStudent(String stuId) {
        // 检查学生是否存在
        StudentInfo existStudent = getById(stuId);
        if (existStudent == null) {
            return false;
        }
        
        return removeById(stuId);
    }
} 